#include "orion20m.h"

void ORION::docklight() {
	int lit;
	lit=evalight->IsActive();
	evalight->Activate(lit?false:true);
	if(!cfg->booting && cfg->verbose) syslog("Lighting for dock #%d has been turned %s.",SelectedUmmuDock+1,(lit?"off":"on"));

}

int ORION::ummu_selectdock(int i) {
	int dc=DockCount();
	if(i>dc-1) i=0;
	if(i<0) i=dc-1;
	DOCKHANDLE Dock=GetDockHandle(i);
	if (!Dock) return -1;
	VECTOR3 dockpos,dockdir,dockrot;
	GetDockParams (Dock, dockpos, dockdir, dockrot);
	SelectedUmmuDock=i;
	Crew.SetActiveDockForTransfer(SelectedUmmuDock);
	Crew.DefineAirLockShape(true, dockpos.x-2.0,dockpos.x+2.0,dockpos.y-2.0,dockpos.y+2.0,dockpos.z-2.0,dockpos.z+2.0);
	EVAPOS=_V(dockpos.x+(dockdir.x*2),dockpos.y+(dockdir.y*2),dockpos.z+(dockdir.z*2));
	/*Crew.SetMembersPosRotOnEVA(
		_V(dockpos.x+(dockdir.x*2),dockpos.y+(dockdir.y*2),dockpos.z+(dockdir.z*2)),
		_V(0,0,0)
	);*/
	
	Crew.SetMembersPosRotOnEVA(
		EVAPOS,
		_V(0,0,0)
	);
	if(!cfg->booting && cfg->verbose) syslog("Dock %d selected.",SelectedUmmuDock+1);
	return SelectedUmmuDock;
}

int ORION::ummu_selectmember(int idx) {
	if(Crew.GetCrewTotalNumber()==0) {
		if(!cfg->booting) syslog("UMMU - No one aboard.");
		return -1;
	}
	if(idx<0) idx=Crew.GetCrewTotalNumber()-1;
	if(idx>Crew.GetCrewTotalNumber()-1) idx=0;
	SelectedUmmuMember=idx;
	char * Name=Crew.GetCrewNameBySlotNumber(SelectedUmmuMember);
	if(!cfg->booting && cfg->verbose) syslog("UMMU - Slot %i  %s \"%s\" aged %i Selected for EVA or Transfer, please press \"E\" to EVA",
		SelectedUmmuMember,Crew.GetCrewMiscIdBySlotNumber(SelectedUmmuMember),
		Name,Crew.GetCrewAgeBySlotNumber(SelectedUmmuMember)
	);
	return SelectedUmmuMember;
}

void ORION::clbkSetClassCaps_UMMu(void)
{
	dprint("clbkSetClassCaps_UMMu: start");
	int initrc=Crew.InitUmmu(GetHandle());
	float UMmuVersion=Crew.GetUserUMmuVersion();
	Crew.SetActiveDockForTransfer(0);
	SelectedUmmuDock=0;
	int rcdefineal=Crew.DefineAirLockShape(TRUE,-1,1,-1,1,40,44);
		//-1,1,40, 3,-2,44);			// Airlock open, 2 meter large 4 meter high 6 meter long (vessel local coordinate)
	EVAPOS=_V(0,0,0);
	int rcsetmempos=Crew.SetMembersPosRotOnEVA(EVAPOS,_V(0,0,0));	// 3 meters in front of ship (z) facing direction of ship (vessel local coordinate)

	    COLOUR4 col_d = {0.5,0.5,0.5,0};
		COLOUR4 col_s = {0.5,0.5,0.5,0};
        COLOUR4 col_a = {0,0,0,0};
        COLOUR4 col_white = {1,1,1,0};
		//le = AddPointLight (_V(0,0,0), 20, 1e-3, 0, 2e-3, col_d, col_s, col_a);
        evalight = AddPointLight (_V(0,0,0), 20, 1e-3, 1e-3, 2e-3, col_d, col_s, col_a);
		//LightEmitter *AddPointLight (const VECTOR3 &pos, double range, double att0, double att1,
		//double att2, COLOUR4 diffuse, COLOUR4 specular, COLOUR4 ambient) const;

		//OBJHANDLE hObj, const VECTOR3 &_pos, double _range, double att0, double att1, double att2
        //le->SetIntensityRef (&th_main_level);
		evalight->SetPositionRef(&EVAPOS);
		evalight->SetIntensity(.1);
		evalight->Activate(false);
        // **************** scramjet definitions ********************
		//void LightEmitter::SetPositionRef  ( const VECTOR3 *  p   )  
		cfg->seldock=0;
		//dock0 = CreateDock (_V( 0.0, 0.0 , 42.0), _V( 0, 0, 1), _V(0,1, 0));
		EVAPOS=_V(0.0+(0*2),0.0+(0*2),42.0+(1*2));

	int rcmaxseat=Crew.SetMaxSeatAvailableInShip(20);

	int dc=DockCount();
	for (int i = 0; i < dc; i++) {
		VECTOR3 dockpos,dockdir,dockrot;
		DOCKHANDLE Dock=GetDockHandle(i);
		GetDockParams (Dock, dockpos, dockdir, dockrot);
		Crew.DeclareActionArea(i,dockpos,2,TRUE,"action_door.wav","Opening airlock");
	}


	//Crew.AddCrewMember("Jordan Collier",41,65,74,"Capt");
	//syslog("ummu init: %d, setal: %d, setmempos: %d, setmax: %d addcapt: %d",initrc,rcdefineal,rcsetmempos,rcmaxseat,rcaddcapt);

	SelectedUmmuMember =0;  // our current selected member
	cUmmuHudDisplay[0] =0;	// Initialisation of UMmu hud char variable
	dHudMessageDelay =0;	// Initialisation of UMmu delay variable
	//strcpy(SendHudMessage(),msg);//Welcome aboard ! E=EVA 1,2=select UMmu A=Open/Close airlock S=info M=add crew");

	// The Add mmu without scenery editor variable see PDF doc
	cAddUMmuToVessel[0]=0;
	dprint("clbkSetClassCaps_UMMu: done");
}


void ORION::ummu_clbkPostStep (double simtt, double simdt, double mjd) {
	int ReturnCode=Crew.ProcessUniversalMMu();
	switch(ReturnCode) {
		case UMMU_TRANSFERED_TO_OUR_SHIP: 
			syslog("%s \"%s\" aged %i was transfered to our ship",
				Crew.GetCrewMiscIdByName(Crew.GetLastEnteredCrewName()),Crew.GetLastEnteredCrewName()
				,Crew.GetCrewAgeByName(Crew.GetLastEnteredCrewName()));
		break;
		case UMMU_RETURNED_TO_OUR_SHIP:
			syslog("%s \"%s\" aged %i entered the ship",
				Crew.GetCrewMiscIdByName(Crew.GetLastEnteredCrewName()),
				Crew.GetLastEnteredCrewName(),Crew.GetCrewAgeByName(Crew.GetLastEnteredCrewName()));
		break;
	}

	int ActionAreaReturnCode=Crew.DetectActionAreaActivated();
	if(ActionAreaReturnCode>-1)
	{
		int dc=DockCount();
		if(ActionAreaReturnCode<=dc) {
			ummu_selectdock(ActionAreaReturnCode);
		}
	}
	/*
				Crew.SetActionAreaText(1,"You are still on the right but this is last keypress");
				// and of course you can change sound, location, state, text, here some examples:
				//Crew.SetActionAreaPos(1,_V(5,0,5)); // change location
				//Crew.SetActionAreaWav(1,"MyAddon\PlayRepaired.wav"); // change sound
				//Crew.SetActionAreaWav(1,"MyAddon\DoorClosed.wav"); // change sound
				//Crew.SetActionAreaText(1,NULL); // sound or text are not mandatory, here we set no text.
				// etc. etc.
	*/

	AddUMmuToVessel();
	cfg->booting=0;
} 

void ORION::ummuret(int Returned) {
		switch(Returned)
		{
		case TRANSFER_TO_DOCKED_SHIP_OK:
			syslog("%s has transferred to \"%s\"",Crew.GetLastEvaedCrewName(),docks[SelectedUmmuDock].dockedname);
			SelectedUmmuMember=0;
			break;
		case EVA_OK:
			syslog("EVA OK - %s left the ship",Crew.GetLastEvaedCrewName());
			SelectedUmmuMember=0;
			break;
		case ERROR_NO_ONE_ON_BOARD:
			syslog("UMMU: ERROR: No one on board, unable to EVA");
			break;
		case ERROR_AIRLOCK_CLOSED:
			syslog("UMMU: ERROR: Airlock is closed, unable to EVA");
			break;
		case ERROR_DOCKED_SHIP_HAVE_AIRLOCK_CLOSED:
			syslog("UMMU: ERROR: Docked ship's airlock is closed, unable to transfer.");
			break;
		case ERROR_DOCKED_SHIP_IS_FULL:
			syslog("UMMU: ERROR: Docked ship is already full.");
			break;
		case ERROR_CREW_MEMBER_NOT_FOUND:
			syslog("UMMU: ERROR: No crew by this name in ship.");
			break;
		case ERROR_DOCKEDSHIP_DONOT_USE_UMMU:
			syslog("UMMU: ERROR: Docked ship does not use UMmu 2.0.");
			break;
		case ERROR_MISC_ERROR_EVAFAILED:
			syslog("UMMU: ERROR: Misc error with UMMU install.");
			break;
		}
}

/*
///////////////////////////////////////////////////////////////////////////////////////////

	//---------------------------------------------------------------------------
	// Ummu Key "A" Switch the virtual UMMU airlock door on/off
	if(key==OAPI_KEY_A&&!KEYMOD_SHIFT(kstate)&&!KEYMOD_CONTROL (kstate))
	{
		// switch state
		Crew.SetAirlockDoorState(!Crew.GetAirlockDoorState());
		// display state
		if(Crew.GetAirlockDoorState()==TRUE)
			strcpy(SendHudMessage(),"Airlock is now open");	
		else
			strcpy(SendHudMessage(),"Airlock is now closed");	
		return 1;
	}

	//---------------------------------------------------------------------------
	// ADD some Fun, Eject the guy, No check of all return code here to keep listing small and clear.
	// Notice eject function doesn't check airlock state at all.
	// GOOD IDEA: Get the Object's handle after ejection with function "GetObjHandleOfLastEVACrew"
	// and add to it one very small tank, thruster and smoke, then fire thruster (see pilot ejection of DGIV)
	// BAD IDEA: Not testing the handle returned by "GetObjHandleOfLastEVACrew" before using may
	// cause a CTD if by any bad luck the pointer is invalid (handle==NULL)
	if(key==OAPI_KEY_ESCAPE&&!KEYMOD_SHIFT(kstate)&&!KEYMOD_CONTROL (kstate))
	{
		if(Crew.EjectCrewMember(Crew.GetCrewNameBySlotNumber(SelectedUmmuMember))==EVA_OK)
			sprintf(SendHudMessage(),"%s EJECTED",Crew.GetLastEvaedCrewName());
		SelectedUmmuMember=0;
		return 1;
	}

	//---------------------------------------------------------------------------
	// Use a different Mesh (type "C" then EVA someone)
	// better idea is to use the new UMMU Id definition
	// look readme.txt in folder "config/UMMUIdConfig"
	if(key==OAPI_KEY_C)
	{
		Crew.SetAlternateMeshToUseForEVASpacesuit("mmu");	// the stock mmu of orbiter located in "meshes/mmu.msh"
		strcpy(SendHudMessage(),"Mesh changed");
		return 1;
	}
*/

char *ORION::SendHudMessage()
{
	dHudMessageDelay=15;
	return cUmmuHudDisplay;
}

//-------------------------------------------------------------------------
// THIS IS FOR ADDING CREW SEE PDF doc "Allow user to add crew to your ship 
// without scenery editor"
bool UMmuCrewAddCallback(void *id, char *str, void *data)
{
	if(strlen(str)<2||strlen(str)>38)
		return false;
	char *cPtr=(char*)data;	if(*cPtr==2){*cPtr=3;strcpy(cPtr+2,str);}
	else if(*cPtr==4){*cPtr=5;strcpy(cPtr+42,str);}
	else if(*cPtr==6){*cPtr=7;strcpy(cPtr+82,str);}return true;
}

void ORION::AddUMmuToVessel(BOOL bStartAdding)
{
	if(bStartAdding==FALSE&&cAddUMmuToVessel[0]==0)
		return;
	if(bStartAdding==TRUE){
		int salut=sizeof(cAddUMmuToVessel);
		memset(cAddUMmuToVessel,0,sizeof(cAddUMmuToVessel));
		cAddUMmuToVessel[0]=1;
	}
	else if(cAddUMmuToVessel[0]==1){
		cAddUMmuToVessel[0]=2;
		oapiOpenInputBox ("Enter new crew's name (or escape)",UMmuCrewAddCallback,0,30,(void*)cAddUMmuToVessel);
	}
	else if(cAddUMmuToVessel[0]==3){
		cAddUMmuToVessel[0]=4;
		oapiOpenInputBox ("Enter crew's age",UMmuCrewAddCallback,0,30,(void*)cAddUMmuToVessel);
	}
	else if(cAddUMmuToVessel[0]==5){
		cAddUMmuToVessel[0]=6;
		oapiOpenInputBox ("Enter function (Capt,Sec,Vip,Sci,Doc,Tech,Crew,Pax)",UMmuCrewAddCallback,0,30,(void*)cAddUMmuToVessel);
	}
	else if(cAddUMmuToVessel[0]==7){
		cAddUMmuToVessel[0]=0;
		int Age=max(5,min(100,atoi(&cAddUMmuToVessel[42])));
		
		dprint("orion: cAddUMmuToVessel(%d): '%s' [0]: %d",sizeof(cAddUMmuToVessel),cAddUMmuToVessel,cAddUMmuToVessel[0]);
		//oapiWriteLog(dstr);

		if(Crew.AddCrewMember(&cAddUMmuToVessel[2],Age,70,70,&cAddUMmuToVessel[82])==TRUE){
			//sprintf(SendHudMessage(),"Crew \"%s\" aged %i added to vessel",&cAddUMmuToVessel[2],Age);
			syslog("UMMU - Crew \"%s\" age %i added to vessel",&cAddUMmuToVessel[2],Age);
		}
		else{
			syslog("UMMU - ERROR: Crew not added (vessel full?)");
			//strcpy(SendHudMessage(),"ERROR: Crew not added (vessel full?)");
		}
	}
}
// END of  "Allow user to add crew to your ship without scenery editor"
//-------------------------------------------------------------------------



